#include "StdAfx.h"
#include "LogView.h"
#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/timeb.h>

LogView::LogView(void)
{
	_File = NULL;
	memset(&_Desc, 0, sizeof(_Desc));
}


LogView::~LogView(void)
{
	if (_File != NULL)
		fclose(_File);
	_File = NULL;
}

HRESULT LogView::Init(LOGVIEWDESC * desc)
{
	LOCKTHIS;
	memcpy(&_Desc, desc, sizeof(LOGVIEWDESC));
	if (_Desc.channelselection & File)
	{
		ASSERT(*_Desc.filename != 0);
		ASSERT(strlen(_Desc.filename) > 1);

		if (*_Desc.filename == 0 || strlen(_Desc.filename) <= 1)
			return E_INVALIDARG;

		errno_t err = 0;
		if (_Desc.flags & CreateNewFile)
			err = fopen_s(&_File, _Desc.filename, "w");
		else if (_Desc.flags & OpenExistingFile)
			err = fopen_s(&_File, _Desc.filename, "a");
		else
		{
			ASSERT(E_INVALIDARG != 0);
			return E_INVALIDARG;
		}
		ASSERT(err == 0);
	}

	return S_OK;
}

void LogView::Out(char * fmt, ...)
{
	StdLog * log = Log;
	LOCKTHIS;
	static char tmpbuf1[50];
	static char tmpbuf2[50];
	static char complete[1100];
	static char output[1000];
	va_list ap;
	va_start(ap, fmt);
	vsprintf_s(output, 1000, fmt, ap);
	va_end(ap);

	_strdate_s( tmpbuf1, 50 );
	_strtime_s( tmpbuf2, 50 );
	sprintf_s(complete, 1100, "%s %s : %s", tmpbuf1, tmpbuf2, output);
	
	// Konsolenausgabe?
	if (_Desc.channelselection & Debug)
		OutputDebugStringA(complete);
	if (_Desc.channelselection & Console)
		printf(complete);
	if (_Desc.channelselection & File)
	{
		size_t len = strlen(complete);
		ASSERT(_File);
		size_t size = fwrite(complete, 1, len, _File);
		ASSERT(size == len);
		fflush(_File);
	}
}


